package com.core.gwt.place.impl;

/**
 * Utility class used for replacing invalid URL token characters.
 * 
 */
public class Encoder {
	/**
	 * Decodes a string using the specified substitutions.
	 */
	public static String decode(String value, final String[][] substitutions) {
		if (null != value) {
			final StringBuilder buffer = new StringBuilder();
			int i = 0;
			while (i < value.length()) {
				boolean match = false;
				for (int j = 0; j < substitutions.length && !match; j++) {
					final String find = substitutions[j][1];
					final String replace = substitutions[j][0];
					if (value.regionMatches(i, find, 0, find.length())) {
						match = true;
						buffer.append(replace);
						i += find.length();
					}
				}
				if (!match) {
					buffer.append(value.charAt(i));
					i++;
				}
			}
			value = buffer.toString();
		}
		return value;
	}

	/**
	 * Encodes a string using the specified substitutions.
	 */
	public static String encode(String value, final String[][] substitutions) {
		if (null != value) {
			final StringBuilder buffer = new StringBuilder();
			int i = 0;
			while (i < value.length()) {
				boolean match = false;
				for (int j = 0; j < substitutions.length && !match; j++) {
					final String find = substitutions[j][0];
					final String replace = substitutions[j][1];
					if (value.regionMatches(i, find, 0, find.length())) {
						match = true;
						buffer.append(replace);
						i += find.length();
					}
				}
				if (!match) {
					buffer.append(value.charAt(i));
					i++;
				}
			}
			value = buffer.toString();
		}
		return value;
	}

}
